package main

import (
	"context"
	"hello_client/pb"
	"log"
	"time"
	"fmt"

	"github.com/hashicorp/consul/api"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/metadata"
)

func doRPC(c pb.HelloClient) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	name := "阿平"

	md := metadata.Pairs("timestamp", time.Now().Format("2006-01-02 15:04:05"))
	ctx = metadata.NewOutgoingContext(ctx, md)

	res, err := c.SayHello(ctx, &pb.Request{Name: name})
	if err != nil {
		log.Fatalf("c.SayHello failed, err:%v\n", err)
	}
	log.Printf("got reply:%v\n", res.Reply)
}

func main() {
	// 先查询一下服务注册中心，找到hello服务对应的地址
	// 1. 连上consul
	consul, err := api.NewClient(api.DefaultConfig())
	if err != nil {
		log.Fatalf(" api.NewClient failed, err:%v\n", err)
	}
	// 2. 查询 hello 服务的所有可用地址
	m, err := consul.Agent().ServicesWithFilter("Service==`hello`")
	if err != nil {
		log.Fatalf(" api.NewClient failed, err:%v\n", err)
	}
	fmt.Printf("%#v\n", m)
	var addr string
	for k, v := range m {
		fmt.Printf("%v:%v\n", k, v)
		addr = fmt.Sprintf("%v:%v", v.Address, v.Port)
		fmt.Println(addr)
		if len(addr) > 0 {
			break
		}
	}
	
	conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))

	if err != nil {
		log.Fatalf("grpc.Dial failed, err:%v\n", err)
	}
	defer conn.Close()
	// 创建rpc client
	client := pb.NewHelloClient(conn)
	log.Printf("client start")

	// 发送普通的RPC调用（一来一回）
	doRPC(client)

}
